﻿Imports System.Xml.Serialization
Imports System.IO

Public Class GenericSerializer

    Public Shared Function Serialize(ByVal obj As Object, ByVal FileName As String) As Boolean
        Try
            Dim xml_serializer As New XmlSerializer(obj.GetType())
            Dim StrWriter As New StreamWriter(FileName)
            xml_serializer.Serialize(StrWriter, obj)
            StrWriter.Close()
            Return True
        Catch ex As Exception
            MsgBox(ex.Message)
            Return False
        End Try
    End Function

    Public Shared Function Serialize(ByVal obj As Object) As String
        Dim xml_serializer As New XmlSerializer(obj.GetType())
        Dim dres As String
        Dim StrWriter As New StringWriter()
        xml_serializer.Serialize(StrWriter, obj)
        dres = StrWriter.ToString()
        StrWriter.Close()
        Return dres
    End Function

    Public Shared Function Serialize(ByVal obj As Object, Type As Type) As String
        Dim xml_serializer As New XmlSerializer(Type)
        Dim dres As String
        Dim StrWriter As New StringWriter()
        xml_serializer.Serialize(StrWriter, obj)
        dres = StrWriter.ToString()
        StrWriter.Close()
        Return dres
    End Function


    Public Shared Function DeserializeFromFile(Of T)(ByRef FileName As String) As T
        Dim deserializer As New System.Xml.Serialization.XmlSerializer(GetType(T))
        Dim StrREader As StreamReader = New StreamReader(FileName)
        Dim FacilityList As T
        FacilityList = DirectCast(deserializer.Deserialize(StrREader), T)
        StrREader.Close()
        StrREader.Dispose()
        Return FacilityList
    End Function

    Public Shared Function DeserializeFromXML(Of T)(ByRef Xmlstring As String) As T
        Dim deserializer As New System.Xml.Serialization.XmlSerializer(GetType(T))
        Dim StrREader As StringReader = New StringReader(Xmlstring)
        Dim FacilityList As T
        FacilityList = DirectCast(deserializer.Deserialize(StrREader), T)
        StrREader.Close()
        StrREader.Dispose()
        Return FacilityList
    End Function

End Class
